﻿using System;
using Vortex;
using Vortex.Drawing;

namespace Vortex.Tutorials.ParallaxEffect {
    public class Camera2D {
        public float Zoom {
            get { return zoom; }
            set {
                zoom = value;
                if (zoom < 0) {
                    zoom = 0;
                }
            }
        }

        public float Rotation;
        public float X;
        public float Y;

        public bool Active {
            get { return this.isActive; }
        }

        public Vector2 Pos {
            get {
                return new Vector2(X, Y);
            }
        }

        public Camera2D() : this(0, 0) { }

		public Camera2D(int x, int y) : this(x, y, new Rect(0, 0, Game.Window.Size.Width, Game.Window.Size.Height)) { }

        public Camera2D(int x, int y, Rect viewPort) {
            X = x;
            Y = y;
            this.viewPort = viewPort;
            transform = Transform2D.Empty;
            Rotation = 0f;
            zoom = 1f;
        }

        public Transform2D TransformMatrix {
            get {
                transform = Transform2D.CreateTranslation(-X, -Y) *
                            Transform2D.CreateRotation(Rotation) *
                            Transform2D.CreateScaling(zoom) *
                            Transform2D.CreateTranslation(viewPort.HalfWidth, viewPort.HalfHeight);

                return transform;
            }
        }

        public void MoveTo(float x, float y, float dampingFactor) {
            isActive = true;

            currentDestiny = new Vector2(x, y);

            this.dampingFactor = dampingFactor;
        }

        public void Update() {
            if (!isActive) {
                return;
            }

            X = MathHelper.Lerp(X, currentDestiny.X, dampingFactor);
            Y = MathHelper.Lerp(Y, currentDestiny.Y, dampingFactor);

            if (isActive && Math.Abs(Pos.X - currentDestiny.X) < 0.1f && Math.Abs(Pos.Y - currentDestiny.Y) < 0.1f) {
                isActive = false;
            }
        }

        private Rect viewPort;
        private float zoom;
        private Transform2D transform;
        private bool isActive;
        private Vector2 currentDestiny;
        private float dampingFactor;

    }
}
